<template>
  <div>
    <el-page-header @back="$router.push({ name: 'UsersIndex' })">
      <template #content>
        <div style="display: flex; align-items: center; justify-content: center">
          <el-avatar :size="32" :src="userInfo.avatar" />
          个人中心
        </div>
      </template>
      <el-descriptions :column="2" size="small">
        <el-descriptions-item label="用户名">{{ userInfo.username }}</el-descriptions-item>
        <el-descriptions-item label="手机">{{ userInfo.phone }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ userInfo.email }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{
          userInfo.gender === '1' ? '男' : '女'
        }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ userInfo.ctime }}</el-descriptions-item>
      </el-descriptions>
      <template #extra>
        <el-button link type="primary" @click="drawer = true">编辑</el-button>
      </template>
    </el-page-header>

    <el-drawer v-model="drawer" title="编辑">
      <el-form ref="formRef" label-position="top" :rules="rules" :model="form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio label="1">男</el-radio>
            <el-radio label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="save">确定</el-button>
          <el-button link @click="drawer = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>
<script setup>
// eslint-disable-next-line object-curly-newline
import { onMounted, ref, shallowRef, reactive } from 'vue';

import { ElMessage } from 'element-plus';

import { getLoginedUserInfoApi, fieldValueExistApi, editLoginedUserApi } from '@/api/users';

const userInfo = ref({});

const drawer = ref(false);

const formRef = shallowRef(null);
// 保存原来的值，在验证的时候对比新值，如果一致就不做远端验证
// const userInfo = shallowRef({});

const form = reactive({
  username: '',
  email: '',
  phone: '',
  gender: '1',
});

const rules = {
  username: [
    {
      required: true,
      message: '用户名必须填写',
      trigger: 'change',
    },
    {
      validator: (rule, value, cb) => {
        if (/^[a-z]{2,18}$/.test(value)) {
          cb();
        } else {
          cb(new Error('用户名必须2-18个字符'));
        }
      },
      trigger: 'change',
    },
    {
      validator: async (rule, value, cb) => {
        if (value === '' || value === userInfo.value.username) cb();
        const res = await fieldValueExistApi({ field: 'username', value });
        if (res.data) {
          cb(new Error('用户名已存在'));
        } else {
          cb();
        }
      },
      trigger: 'blur',
    },
  ],
  email: [
    {
      required: true,
      message: '邮箱必须填写',
      trigger: 'change',
    },
    {
      validator: (rule, value, cb) => {
        if (
          /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
            value,
          )
        ) {
          cb();
        } else {
          cb(new Error('邮箱格式错误'));
        }
      },
      trigger: 'change',
    },
    {
      validator: async (rule, value, cb) => {
        if (value === '' || value === userInfo.value.email) cb();
        const res = await fieldValueExistApi({ field: 'email', value });
        if (res.data) {
          cb(new Error('邮箱已存在'));
        } else {
          cb();
        }
      },
      trigger: 'blur',
    },
  ],
  phone: [
    {
      required: true,
      message: '手机必须填写',
      trigger: 'change',
    },
    {
      validator: (rule, value, cb) => {
        if (/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(value)) {
          cb();
        } else {
          cb(new Error('手机格式错误'));
        }
      },
      trigger: 'change',
    },
    {
      validator: async (rule, value, cb) => {
        if (value === '' || value === userInfo.value.phone) cb();
        const res = await fieldValueExistApi({ field: 'phone', value });
        if (res.data) {
          cb(new Error('手机已存在'));
        } else {
          cb();
        }
      },
      trigger: 'blur',
    },
  ],
  password: [
    {
      required: true,
      message: '密码必须填写',
      trigger: 'change',
    },
    {
      validator: (rule, value, cb) => {
        const len = value.length;
        if (len >= 6 && len <= 18) {
          cb();
        } else {
          cb(new Error('密码必须6-18个字符'));
        }
      },
      trigger: 'change',
    },
  ],
  cpassword: [
    {
      validator: (rule, value, cb) => {
        if (value === form.password) {
          cb();
        } else {
          cb(new Error('两次密码输入不一致'));
        }
      },
      trigger: 'change',
    },
  ],
};

onMounted(async () => {
  // 获取登录用户信息
  const res = await getLoginedUserInfoApi();
  userInfo.value = res.data;

  // 数据回填
  form.username = userInfo.value.username;
  form.email = userInfo.value.email;
  form.phone = userInfo.value.phone;
  form.gender = userInfo.value.gender;
});

const save = async () => {
  await formRef.value.validate();

  // 编辑
  await editLoginedUserApi({
    username: form.username,
    gender: form.gender,
    phone: form.phone,
    email: form.email,
  });

  ElMessage.success('编辑成功');
  drawer.value = false;
  // 更新页面
  // 获取登录用户信息
  const res = await getLoginedUserInfoApi();
  userInfo.value = res.data;
};
</script>
